<template>
  <div class="map-container">
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import 'echarts-gl'

const chartRef = ref<HTMLElement>()
let chart: echarts.ECharts | null = null

interface LineItem {
  coords: number[][]
  name: string
  lineStyle: {
    width: number
  }
}

// 生成连线数据
const generateLines = (): LineItem[] => {
  return [
    {
      coords: [[113.23, 23.16], [121.48, 31.22]], // 广州-上海
      name: '广州-上海',
      lineStyle: { width: 2 }
    },
    {
      coords: [[113.23, 23.16], [116.46, 39.92]], // 广州-北京
      name: '广州-北京',
      lineStyle: { width: 2 }
    },
    {
      coords: [[114.07, 22.62], [104.06, 30.67]], // 深圳-成都
      name: '深圳-成都',
      lineStyle: { width: 2 }
    }
  ]
}

// 生成散点数据
const generateScatterData = () => {
  return [
    { name: '广州', value: [113.23, 23.16] },
    { name: '上海', value: [121.48, 31.22] },
    { name: '北京', value: [116.46, 39.92] },
    { name: '深圳', value: [114.07, 22.62] },
    { name: '成都', value: [104.06, 30.67] }
  ]
}

const initChart = async () => {
  if (!chartRef.value) return
  
  const mapData = await fetch('https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json')
    .then(res => res.json())
  
  echarts.registerMap('china', mapData)
  chart = echarts.init(chartRef.value)
  
  const option = {
    backgroundColor: '#041B35',
    geo: [{
      // 底图配置
      map: 'china',
      aspectScale: 0.85,
      layoutCenter: ['50%', '52%'],
      layoutSize: '100%',
      roam: true,
      scaleLimit: {
        min: 1,
        max: 2
      },
      itemStyle: {
        normal: {
          areaColor: {
            type: 'linear-gradient',
            x: 0,
            y: 1200,
            x2: 1000,
            y2: 0,
            colorStops: [{
              offset: 0,
              color: 'rgba(11, 26, 55, 0.95)'
            }, {
              offset: 1,
              color: 'rgba(3, 56, 85, 0.95)'
            }],
          },
          borderColor: 'rgba(0, 246, 255, 0.2)',
          borderWidth: 5
        }
      }
    }, {
      // 上层地图
      map: 'china',
      aspectScale: 0.85,
      layoutCenter: ['50%', '50%'],
      layoutSize: '100%',
      roam: true,
      scaleLimit: {
        min: 1,
        max: 2
      },
      itemStyle: {
        normal: {
          areaColor: {
            type: 'linear-gradient',
            x: 0,
            y: 1200,
            x2: 1000,
            y2: 0,
            colorStops: [{
              offset: 0,
              color: 'rgba(21, 46, 110, 0.95)'
            }, {
              offset: 1,
              color: 'rgba(6, 115, 173, 0.95)'
            }],
          },
          borderColor: 'rgba(0, 246, 255, 0.8)',
          borderWidth: 5
        }
      }
    }],
    series: [
      // 迁移线路图层 - 发光效果
      {
        name: 'lines',
        type: 'lines',
        coordinateSystem: 'geo',
        geoIndex: 1, // 关联到上层地图
        zlevel: 3,
        effect: {
          show: true,
          period: 6,
          trailLength: 0.7,
          color: '#0CFFE6',
          symbolSize: 3
        },
        lineStyle: {
          normal: {
            color: '#0CFFE6',
            width: 0,
            curveness: 0.3
          }
        },
        data: generateLines()
      },
      // 迁移线路底层
      {
        name: 'lines2',
        type: 'lines',
        coordinateSystem: 'geo',
        geoIndex: 1, // 关联到上层地图
        zlevel: 2,
        effect: {
          show: true,
          period: 6,
          trailLength: 0,
          symbol: 'arrow',
          symbolSize: 7
        },
        lineStyle: {
          normal: {
            color: '#0CFFE6',
            width: 1,
            opacity: 0.4,
            curveness: 0.3
          }
        },
        data: generateLines()
      },
      // 散点图层
      {
        name: 'scatter',
        type: 'effectScatter',
        coordinateSystem: 'geo',
        geoIndex: 1, // 关联到上层地图
        zlevel: 4,
        symbolSize: 10,
        rippleEffect: {
          brushType: 'stroke'
        },
        label: {
          normal: {
            show: true,
            position: 'right',
            formatter: '{b}',
            color: '#0CFFE6'
          }
        },
        itemStyle: {
          normal: {
            color: '#0CFFE6',
            shadowBlur: 10,
            shadowColor: '#0CFFE6'
          }
        },
        data: generateScatterData()
      }
    ]
  }

  chart.setOption(option)

  // 监听地图拖动事件
  let isDragging = false;
  let lastX = 0;
  let lastY = 0;

  // 监听鼠标按下事件
  chart.getZr().on('mousedown', function(params) {
    isDragging = true;
    lastX = params.offsetX;
    lastY = params.offsetY;
  });

  // 监听鼠标移动事件
  chart.getZr().on('mousemove', function(params) {
    if (!isDragging) return;
    
    const deltaX = params.offsetX - lastX;
    const deltaY = params.offsetY - lastY;
    lastX = params.offsetX;
    lastY = params.offsetY;

    const option = chart.getOption();
    
    // 同步更新两个地图图层的视角
    option.geo.forEach((geo: any) => {
      const center = geo.center || [104.5, 36.5];
      const zoom = geo.zoom || 1;
      
      // 根据缩放级别调整移动速度
      const moveSpeed = 0.2 / zoom;
      
      geo.center = [
        center[0] - deltaX * moveSpeed,
        center[1] + deltaY * moveSpeed
      ];
    });
    
    chart.setOption(option);
  });

  // 监听鼠标松开事件
  chart.getZr().on('mouseup', function() {
    isDragging = false;
  });
  chart.getZr().on('globalout', function() {
    isDragging = false;
  });

  // 监听缩放事件
  chart.getZr().on('mousewheel', function(params) {
    const option = chart.getOption();
    const delta = params.wheelDelta > 0 ? 1.1 : 1 / 1.1;
    
    // 同步更新两个地图图层的缩放
    option.geo.forEach((geo: any) => {
      const zoom = geo.zoom || 1;
      geo.zoom = Math.max(1, Math.min(2, zoom * delta));
    });
    
    chart.setOption(option);
  });

  // 修改事件处理，使用 geoRoam 事件
  chart.on('geoRoam', function(params) {
    if (params.geoIndex === 1) {  // 只处理上层地图的事件
      const option = chart.getOption();
      // 将上层地图的视图状态同步到底图
      option.geo[0].center = option.geo[1].center;
      option.geo[0].zoom = option.geo[1].zoom;
      chart.setOption(option);
    }
  });
}

// 处理窗口大小变化
const handleResize = () => {
  chart?.resize()
}

onMounted(() => {
  initChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  chart?.dispose()
  window.removeEventListener('resize', handleResize)
})
</script>

<style lang="scss" scoped>
.map-container {
  width: 100%;
  height: 100vh;
  background-color: #041B35;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  
  .chart {
    width: 100%;
    height: 100%;
  }
}
</style>
